package org.ithasu.filpilote.data.entities;

import java.util.ArrayList;
import java.util.List;

import org.ithasu.tools.data.Entity;
import org.ithasu.tools.net.JSONTools;
import org.ithasu.tools.net.JSONTools.JSONContext;
import org.ithasu.tools.net.JSONTools.JSONEntity;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Program implements JSONEntity, Entity {

	private final static String JSON_PROPERTY_PROGRAM_INDEX = "index";
	private final static String JSON_PROPERTY_PROGRAM_NAME = "name";
	private final static String JSON_PROPERTY_PROGRAM_RULES = "rules";

	private long index;
	private String name;
	private final ArrayList<Rule> rules = new ArrayList<Rule>();

	public Program(JSONContext context, JSONObject o) {
		parseJSON(context, o);
	}

	// -- Entity ----------------------------------------

	@Override
	public long getId() {
		return index;
	}

	// -- Properties ----------------------------------------

	public String getName() {
		return name;
	}

	public ArrayList<Rule> getRules() {
		return rules;
	}

	// -- JSON ----------------------------------------

	@SuppressWarnings("unchecked")
	@Override
	public JSONObject toJSON(JSONContext context) {
		JSONObject o = new JSONObject();
		o.put(JSON_PROPERTY_PROGRAM_INDEX, index);
		o.put(JSON_PROPERTY_PROGRAM_NAME, name);
		JSONArray rs = new JSONArray();
		for (Rule r : rules) {
			rs.add(r.toJSON(context));
		}
		o.put(JSON_PROPERTY_PROGRAM_RULES, rs);
		return o;
	}

	@Override
	public void parseJSON(JSONContext context, JSONObject o) {
		this.index = JSONTools.getProperty(Long.class, o, JSON_PROPERTY_PROGRAM_INDEX, -1l);
		this.name = JSONTools.getProperty(String.class, o, JSON_PROPERTY_PROGRAM_NAME);
		this.rules.clear();
		List<?> rs = JSONTools.getProperty(JSONArray.class, o, JSON_PROPERTY_PROGRAM_RULES);
		if (rs != null) {
			for (Object r : rs) {
				JSONObject ro = JSONTools.safeCast(JSONObject.class, r);
				this.rules.add(new Rule(context, ro));
			}
		}
	}

}
